import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {Router} from '@angular/router';
import {HttpClient} from '@angular/common/http';
import {timer} from 'rxjs';
import {AppService} from '../../service/app/app.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css'],
  providers: [
    FormBuilder,
  ]
})
export class LoginComponent implements OnInit {
  validateForm: FormGroup;
  errorMessage: string;
  showMessage = false;
  index = 1;
  loginImg = require('../../../assets/data_center.svg');
  constructor(private fb: FormBuilder,
              private http: HttpClient,
              private appSerivce: AppService,
              private router: Router) {}

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      email: [null, [Validators.required]],
      passwd: [null, [Validators.required]],
    });
  }
  submitForm(): void {
  }
  enterRegister() {
    this.router.navigate(['register']).catch();
  }
  forgetPassword() {
    this.router.navigate(['forget']).catch();
  }
  login() {
    this.appSerivce.post(this.appSerivce.urls.login, this.validateForm.value).subscribe((resp: any) => {
      const userInfo = resp.body;
      if (userInfo.ret === 1) {
        localStorage.setItem('email', this.validateForm.value.email);
        localStorage.setItem('passwd', this.validateForm.value.passwd);
        localStorage.setItem('token', userInfo.data.token);
        localStorage.setItem('user_id', userInfo.data.user_id);
        localStorage.setItem('status', 'off');
        this.router.navigate(['home']).catch();
      } else {
        this.showMessage = true;
        this.errorMessage = userInfo.msg;
        this.hideErrorMessage(1000);
      }
    });
  }
  hideErrorMessage(time) {
    timer(time).subscribe(() => {
      this.showMessage = false;
      this.errorMessage = '';
    });
  }
}
